package com.wpf.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.wpf.system.entity.Menu;
import com.wpf.system.entity.User;
import com.wpf.system.security.LoginUser;
import com.wpf.system.service.MenuService;
import com.wpf.system.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private UserService userService;

    @Resource
    private MenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String nid) throws UsernameNotFoundException {
        // 认证
        User user = userService.getUserByNid(nid);
        if(ObjectUtil.isNull(user)){ // 用户不存在
            throw new UsernameNotFoundException("用户不存在");
        }
        // 授权
        // 查询用户所有权限
        List<Menu> menuList = menuService.getUserMenuById(user.getId());
        // 获取所有的权限字段并转换为数组
        String[] strings = menuList.stream().filter(Objects::nonNull).map(Menu::getPerms).filter(Objects::nonNull).toArray(String[]::new);
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(strings);
        // 设置权限
        user.setAuthorities(authorityList);
        // 设置菜单列表
        user.setPermissionList(menuList);

        return new LoginUser(user);

    }
}
